#!/bin/bash
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Original file
# https://github.com/discourse/discourse_docker/blob/master/image/base/install-nginx

set -e

# version check: https://nginx.org/en/download.html
VERSION=1.17.9
HASH="7dd65d405c753c41b7fdab9415cfb4bdbaf093ec6d9f7432072d52cb7bcbb689"

cd /usr/src
git clone https://github.com/bagder/libbrotli
cd libbrotli
./autogen.sh
./configure
make install

cd /usr/src
curl -O https://nginx.org/download/nginx-$VERSION.tar.gz
sha256sum nginx-$VERSION.tar.gz
echo "$HASH nginx-$VERSION.tar.gz" | sha256sum -c
tar zxf nginx-$VERSION.tar.gz
cd nginx-$VERSION

cd /usr/src
# this is the reason we are compiling by hand...
git clone https://github.com/google/ngx_brotli.git
# now ngx_brotli has brotli as a submodule
cd /usr/src/ngx_brotli
git submodule update --init

cd /usr/src/nginx-$VERSION
# ignoring depracations with -Wno-deprecated-declarations while we wait for this https://github.com/google/ngx_brotli/issues/39#issuecomment-254093378
./configure --with-cc-opt='-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -Wno-deprecated-declarations' --with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_addition_module --with-http_dav_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_v2_module --with-http_sub_module --with-stream --with-stream_ssl_module --with-mail --with-mail_ssl_module --with-threads --add-module=/usr/src/ngx_brotli

make install

mv /usr/share/nginx/sbin/nginx /usr/sbin

cd /
rm -fr /etc/nginx/modules-enabled/*

mkdir -p /var/nginx/cache

ldconfig

